using System.Text.Json;
using Microsoft.Extensions.Configuration;

namespace WeatherSDK;

/// <summary>
/// 基础的API提供者
/// </summary>
public abstract class BaseApiProvider
{
    /// <summary>
    /// 配置管理
    /// </summary>
    private readonly IConfigurationRoot _configuration;

    /// <summary>
    /// 默认的JSON序列化选项
    /// </summary>
    private readonly JsonSerializerOptions _jsonSerializerOptions = new(JsonSerializerDefaults.Web);

    private Func<JsonSerializerOptions> _jsonSerializerOptionsFunc;
    
    /// <summary>
    /// 设置超时时间
    /// </summary>
    public uint Timeout { get; set; } = 60;

    /// <summary>
    /// 构造
    /// </summary>
    protected BaseApiProvider()
    {
        if (File.Exists("appsettings.json"))
        {
            _configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
        }
    }

    /// <summary>
    /// 读取配置
    /// </summary>
    /// <param name="key">配置项名称</param>
    /// <returns>配置项值</returns>
    protected string ReadConfig(string key)
    {
        return _configuration?[$"WeatherSDK:{key}"];
    }

    /// <summary>
    /// 设置JSON序列化选项
    /// </summary>
    public Func<JsonSerializerOptions> JsonSerializerOptionsFunc
    {
        set => _jsonSerializerOptionsFunc = value;
    }

    /// <summary>
    /// 获取JSON序列化选项
    /// </summary>
    /// <returns></returns>
    protected JsonSerializerOptions GetJsonSerializerOptions()
    {
        var jsonSerializerOptions = _jsonSerializerOptionsFunc?.Invoke();
        return jsonSerializerOptions ?? _jsonSerializerOptions;
    }
}